// pages/crowdFunding/detail/detail.js
const common = require('../../../utils/util.js')
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userId: null,
        crowdId: null,
        crowdInfo: null,
        navType: 1,
        moneyType: 1,
        num: 1,
        money: 8.8,
        showPay: false,
        successPay: false,
        shareClick: false,
        ewmCode: '',
        previewImg: '',
        showShareImg: false,
        remainDay: 0,
        remainHour: 0,
        remainMinute: 0,
        remainSecond: 0,
        overTime: false,
        ruleImg: '',
        newGoods: [],
        shareImg: '',
        relayImg: '',
        isLoading: false
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.setData({
            crowdId: options.crowdFundingId,
            userId: wx.getStorageSync('userId')
        })
        if (options.userShare) {
            wx.setStorageSync('userShare', options.userShare)
            let data = {
                belong_refer: options.userShare
            }
            common.post('User/set_belong_refer', data).then(function(res) {}).catch(function(e) {})
        }
        this.getCrowdInfo()
        this.getRuleImg()
        this.getShareImg()
        this.getRelayImg()
        this.getEwmCode()
        this.getNewGoods()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
        common.refresh()
        setTimeout(function() {
            wx.stopPullDownRefresh()
        }, 2000)
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {
        let userId = wx.getStorageSync('userId')
        let relayImg = this.data.relayImg
        let crowdId = this.data.crowdId
        if (userId) {
            return {
                title: '我怀揣着梦想和那颗炙热的心，期盼大家能助我一臂之力一同为我赋能。（还能尊享一年0利白领喔~）',
                path: '/pages/crowdFunding/detail/detail?crowdFundingId=' + crowdId + '&userShare=' + userId,
                imageUrl: relayImg
            }
        }
    },

    myCatchTouch: function() {
        return
    },

    getTime: function() {
        let today = new Date(),
            h = today.getHours(),
            m = today.getMinutes(),
            s = today.getSeconds()
        let stopTime = new Date(this.data.crowdInfo.end_time.replace(/-/g, '/')),
            stopH = stopTime.getHours(),
            stopM = stopTime.getMinutes(),
            stopS = stopTime.getSeconds()
        let remainTime = stopTime.getTime() - today.getTime()
        if (remainTime < 0) {
            this.setData({
                overTime: true
            })
            clearInterval(this.time)
            return
        }
        let remainDay = parseInt(remainTime / (60 * 60 * 24 * 1000))
        this.setData({
            remainDay: remainDay
        })
        let remainTimeD =
            parseInt(remainTime) -
            parseInt(remainDay * 60 * 60 * 24 * 1000)
        let remainHour = parseInt(remainTimeD / (60 * 60 * 1000))
        this.setData({
            remainHour: remainHour
        })
        let remainTimeH = remainTimeD - remainHour * 60 * 60 * 1000
        let remainMinute = parseInt(remainTimeH / (60 * 1000))
        this.setData({
            remainMinute: remainMinute
        })
        let remainTimeM = remainTimeH - remainMinute * 60 * 1000
        let remainSecond = parseInt(
            (remainTime -
                remainDay * 60 * 60 * 24 * 1000 -
                remainHour * 60 * 60 * 1000 -
                remainMinute * 60 * 1000) /
            1000
        )
        this.setData({
            remainSecond: remainSecond
        })
    },

    getCrowdInfo: function() {
        wx.showLoading({
            title: '加载中'
        })
        const that = this
        let data = {
            crowd_id: this.data.crowdId,
            paramter: 1
        }
        common.post('Crowd/crowd_list', data).then(function(res) {
            wx.hideLoading()
            if (res.code == 204) {
                return
            }
            if (res[0].img && res[0].img.length > 0) {
                res[0].img = res[0].img.split(',')
            }
            that.setData({
                crowdInfo: res[0]
            })
            that.getTime()
            that.time = setInterval(that.getTime, 1000)
        }).catch(function(e) {})
    },

    getEwmCode: function() {
        const that = this
        let data = {
            crowdFundingId: this.data.crowdId
        }
        common.post('Qrcodes/create_crowd', data).then(function(res) {
            that.setData({
                ewmCode: res
            })
        }).catch(function(e) {})
    },

    getShareImg: function() {
        const that = this
        let data = {
            activity: 785,
            images_id: 12
        }
        common.post('Images/get_img', data).then(function(res) {
            that.setData({
                shareImg: res[0].images
            })
        }).catch(function(e) {})
    },

    getRuleImg: function() {
        const that = this
        let data = {
            activity: 785,
            images_id: 10
        }
        common.post('Images/get_img', data).then(function(res) {
            that.setData({
                ruleImg: res[0].images
            })
        }).catch(function(e) {})
    },

    getRelayImg: function() {
        const that = this
        let data = {
            activity: 785,
            images_id: 13
        }
        common.post('Images/get_img', data).then(function(res) {
            that.setData({
                relayImg: res[0].images
            })
        }).catch(function(e) {})
    },

    getNewGoods: function() {
        const that = this
        let data = {
            activity: 785,
            is_goods: 99,
            order_by: 'add_time',
            asc: 2,
            page: 0,
            limit: 6
        }
        common.post('Goodslist/goods_list', data).then(function(res) {
            if (res.code == 204) {
                that.setData({
                    newGoods: []
                })
            } else {
                that.setData({
                    newGoods: res
                })
            }
        }).catch(function(e) {})
    },

    navClick: function(e) {
        if (this.data.navType == e.currentTarget.dataset.type) {
            return
        }
        this.setData({
            navType: e.currentTarget.dataset.type
        })
    },

    showPay: function() {
        var animation = wx.createAnimation({
            duration: 500,
            timingFunction: "ease",
            delay: 0
        })
        this.animation = animation
        animation.translateY(1500).step()
        this.setData({
            animationData: animation.export(), // export 方法每次调用后会清掉之前的动画操作。
            showPay: true
        })
        setTimeout(() => {
            animation.translateY(0).step()
            this.setData({
                animationData: animation.export() // export 方法每次调用后会清掉之前的动画操作。
            })
        }, 200)
    },

    closeShowPay: function() {
        var animation = wx.createAnimation({
            duration: 500,
            timingFunction: "ease",
            delay: 0
        })
        this.animation = animation
        animation.translateY(1500).step()
        this.setData({
            animationData: animation.export(),
        })
        setTimeout(function() {
            animation.translateY(0).step()
            this.setData({
                animationData: animation.export(),
                showPay: false
            })
        }.bind(this), 200)
    },

    goSupportList: function(e) {
        wx.navigateTo({
            url: '/pages/crowdFunding/support/support?crowdFundingId=' + e.currentTarget.dataset.id
        })
    },

    goRules: function() {
        wx.navigateTo({
            url: '/pages/crowdFunding/rules/rules'
        })
    },

    moneyTypeChange: function(e) {
        if (this.data.moneyType == e.currentTarget.dataset.type) {
            return
        }
        this.setData({
            moneyType: e.currentTarget.dataset.type,
            money: e.currentTarget.dataset.money
        })
    },

    moneyInput: function(e) {
        this.setData({
            money: e.detail.value
        })
    },

    numMinus: function() {
        if (this.data.num == 1) {
            return
        }
        this.setData({
            num: this.data.num - 1
        })
    },

    numAdd: function() {
        this.setData({
            num: this.data.num + 1
        })
    },

    goPay: function() {
        if (this.data.isLoading) {
            return
        }
        if (this.data.money == 'null') {
            wx.showToast({
                title: '请填写金额',
                icon: 'none',
                duration: 2000
            })
            return
        }
        this.setData({
            isLoading: true
        })
        wx.showLoading({
            title: '请稍后'
        })
        const that = this
        wx.login({
            success(res) {
                if (res.code) {
                    let data = {
                        crowd_id: that.data.crowdInfo.crowd_id,
                        num: that.data.num,
                        price: that.data.money,
                        code: res.code,
                        pay_client: 1
                    }
                    console.log(data)
                    common.post('Crowd/crowd_help', data).then(function(res) {
                        wx.hideLoading()
                        that.setData({
                            isLoading: false
                        })
                        if (res.code == 204) {
                            wx.showModal({
                                title: '提示',
                                content: res.error,
                                showCancel: false,
                                success(res) {}
                            })
                        } else {
                            wx.requestPayment({
                                timeStamp: res.timeStamp,
                                nonceStr: res.nonceStr,
                                package: res.package,
                                signType: res.signType,
                                paySign: res.paySign,
                                success(res) {
                                    wx.showModal({
                                        title: '提示',
                                        content: '赋能成功',
                                        showCancel: false,
                                        success(res) {
                                            if (res.confirm) {
                                                that.getCrowdInfo()
                                                that.closeShowPay()
                                                that.setData({
                                                    successPay: true
                                                })
                                            }
                                        }
                                    })
                                },
                                fail(res) {
                                    wx.showModal({
                                        title: '提示',
                                        content: '支付失败',
                                        showCancel: false,
                                        success(res) {}
                                    })
                                }
                            })
                        }
                    }).catch(function(e) {})
                }
            }
        })
    },

    closeSuccessPay: function() {
        this.setData({
            successPay: false
        })
    },

    goHome: function() {
        wx.switchTab({
            url: '/pages/index/index'
        })
    },

    goShare: function() {
        this.setData({
            shareClick: true
        })
    },

    goGoodsMore: function() {
        wx.switchTab({
            url: '/pages/index/index'
        })
    },

    cancleShare: function() {
        this.setData({
            shareClick: false
        })
    },

    imgShare: function() {
        this.setData({
            showShareImg: true,
            shareClick: false
        })
        this.createImg()
    },

    closeImgShare: function() {
        this.setData({
            showShareImg: false
        })
    },

    createImg: function() {
        wx.showLoading({
            title: '正在生成图片...',
        })
        const that = this
        const wxGetImageInfo = this.promisify(wx.getImageInfo)
        Promise.all([
            wxGetImageInfo({
                src: that.data.shareImg
            }),
            wxGetImageInfo({
                src: 'https:' + that.data.ewmCode.split(':')[1]
            })

        ]).then(res => {
            const ctx = wx.createCanvasContext('shareCanvas')
            ctx.drawImage(res[0].path, 0, 0, 750, 1234)
            ctx.drawImage(res[1].path, 520, 1053, 150, 150)
            ctx.draw(false, function(e) {
                const wxCanvasToTempFilePath = that.promisify(wx.canvasToTempFilePath)
                wxCanvasToTempFilePath({
                    canvasId: 'shareCanvas',
                    x: 0,
                    y: 0,
                    width: 750,
                    height: 1234,
                    destWidth: 750,
                    destHeight: 1234
                }, this).then(res => {
                    wx.hideLoading()
                    that.setData({
                        previewImg: res.tempFilePath
                    })
                })
            })
        })
    },

    downloadImg: function() {
        const that = this
        wx.saveImageToPhotosAlbum({
            filePath: this.data.previewImg,
            success: function(data) {
                wx.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000
                })
                that.closeShare()
            },
            fail: function(err) {
                if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                    wx.showModal({
                        title: '用户未授权',
                        content: '请先开启保存到相册权限，开启后即可保存图片',
                        success(res) {
                            if (res.confirm) {
                                wx.openSetting({
                                    success(settingdata) {
                                        if (settingdata.authSetting['scope.writePhotosAlbum']) {
                                            wx.saveImageToPhotosAlbum({
                                                filePath: that.data.previewImg,
                                                success(res) {
                                                    wx.showToast({
                                                        title: '保存成功',
                                                        icon: 'success',
                                                        duration: 2000
                                                    })
                                                    that.closeShare()
                                                }
                                            })
                                        } else {
                                            wx.showToast({
                                                title: '保存图片失败，请确认开启授权后重新保存图片',
                                                icon: 'none',
                                                duration: 2000
                                            })
                                        }
                                    }
                                })
                            } else if (res.cancel) {
                                wx.showToast({
                                    title: '保存图片失败，请确认开启授权后重新保存图片',
                                    icon: 'none',
                                    duration: 2000
                                })
                            }
                        }
                    })
                }
            }
        })
    },

    promisify: function(api) {
        return (options, ...params) => {
            return new Promise((resolve, reject) => {
                const extras = {
                    success: resolve,
                    fail: reject
                }
                api({
                    ...options,
                    ...extras
                }, ...params)
            })
        }
    },

    circleImg: function(ctx, img, x, y, r) {
        ctx.beginPath()
        ctx.save();
        var d = 2 * r;
        var cx = x + r;
        var cy = y + r;
        ctx.arc(cx, cy, r, 0, 2 * Math.PI);
        ctx.clip();
        ctx.drawImage(img, x, y, d, d);
        ctx.restore();
    },

    previewImg: function(e) {
        wx.previewImage({
            current: e.currentTarget.dataset.img, // 当前显示图片的http链接
            urls: e.currentTarget.dataset.imgs // 需要预览的图片http链接列表
        })
    },

    goGoodsDetail: function(e) {
        wx.navigateTo({
            url: '/pages/goods/goodsDetail/goodsDetail?goodsId=' + e.currentTarget.dataset.id,
        })
    }
})